﻿/**********************************************************************
/// <summary>
// Name of File     :   AddEditUser.cs
// Author           :   Parminder Singh
// Create date      :   17th Sep 2011
/// </summary>
************************************************************************/

using System;
using Crystal.Common.Model;
using CrystalAdmin.Presenter;
using Crystal.CLL;
using System.Windows.Forms;
using System.Drawing;
using System.Configuration;

namespace CrystalAdmin.View
{
    public partial class AddEditUser : BaseForm, IAddUpdateUserView
    {
        #region Fields
        public event VoidEventHandler EveSaveUser;
        public event CheckUserNameEventHandler CheckUserName;
        public event CheckEmailEventHandler CheckEmailAddress;
        private IAddUpdateUserPresenter AddUpdatePresenter;
        private USR_Users user;
        private ValidationManager.RequiredFieldValidator reqFirstName;
        private ValidationManager.RequiredFieldValidator reqLastName;
        private ValidationManager.RequiredFieldValidator reqUserName;
        private ValidationManager.RequiredFieldValidator reqPassword;
        private ValidationManager.RequiredFieldValidator reqConfirmPassword;
        private ValidationManager.CompareValidator cmpPassword;
        private ValidationManager.RegularExpressionValidator regEmail;
        private ValidationManager.RegularExpressionValidator regPassword;
        private bool isSaved = false;
        private bool isNewUser = false;
        private int UserId = 0;
        public ViewMode viewMode;
        #endregion

        #region Properties
        public USR_Users CurrentUser
        {
            get { return user; }
            set
            {
                user = value;
            }
        }
        #endregion

        #region Constructor
        public AddEditUser(USR_Users CurrentUser)
        {
            InitializeComponent();
            user = CurrentUser;
            AddUpdatePresenter = new AddUpdateUserPresenter(this);
            GetValidatedControls();
        }
        #endregion

        #region Events

        #region Form

        private void AddEditUser_Load(object sender, EventArgs e)
        {
            try
            {
                if (CurrentUser != null)
                {
                    txtFirstName.Text = CurrentUser.FirstName;
                    txtLastName.Text = CurrentUser.LastName;
                    txtUserName.Text = CurrentUser.UserName;
                    txtPassword.Text = CurrentUser.Password;
                    txtConfirmPassword.Text = CurrentUser.Password;
                    txtEmailAddress.Text = CurrentUser.EMailAddress;
                    if (CurrentUser.UserStatus == UserStatus.EXEMP.ToString())
                    {
                        chk.Checked = true;
                    }
                }
                else
                {
                    CheckEmptyTexBox();
                }
            }
            catch (Exception ex)
            {
                this.LogErrorToDatabase(ex);
            }
        }

        private void AddEditUser_FormClosing(object sender, FormClosingEventArgs e)
        {
            try
            {
                if (!isSaved)
                {
                    CloseAddEditUserForm(e);
                }
                if (isSaved)
                    UnloadEvents();
            }
            catch (Exception ex)
            {
                this.LogErrorToDatabase(ex);
            }
        }

        private void AddEditUser_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (txtEmailAddress.Focused)
            {
                if (Char.IsUpper(e.KeyChar))
                {
                    e.KeyChar = Char.ToLower(e.KeyChar);
                }
            }
        }

        private void AddEditUser_FormClosed(object sender, FormClosedEventArgs e)
        {
            if (isNewUser)
            {
                for (int i = 0; i <= Application.OpenForms.Count - 1; i++)
                {
                    if ((Application.OpenForms[i].Name == "ListUsers"))
                    {
                        ((ListUsers)Application.OpenForms[i]).GetAllUsersBySearchText();
                    }
                }
            }
        }

        #endregion

        #region TextBoxEvents

        private void txtFirstName_Leave(object sender, EventArgs e)
        {
            if (txtUserName.Text.Trim() == string.Empty)
            {
                GetUserName();
            }
            EnableDisableSaveButton(txtFirstName);
        }

        private void txtFirstName_TextChanged(object sender, EventArgs e)
        {
            if (txtFirstName.Text.Length == 1)
            {
                txtUserName.Text = txtFirstName.Text.Trim() + txtLastName.Text.Trim();
                txtEmailAddress.Text = GetEmailAddress(txtUserName.Text.Trim()).ToLower();
            }
            if (txtFirstName.Text.Length > 0)
            {
                EnableDisableSaveButton(txtFirstName);
            }
        }

        private void txtLastName_TextChanged(object sender, EventArgs e)
        {
            if (txtLastName.Text.Length > 0)
            {
                GetUserName();
                EnableDisableSaveButton(txtLastName);
            }
        }

        private void txtLastName_Leave(object sender, EventArgs e)
        {
            if (txtUserName.Text.Trim() == string.Empty || txtUserName.Text.Trim().Length == 1)
            {
                GetUserName();
            }
            //EnableDisableSaveButton();
        }

        private void txtPassword_TextChanged(object sender, EventArgs e)
        {
            EnableDisableSaveButton(txtPassword);
        }

        private void txtUserName_TextChanged(object sender, EventArgs e)
        {
            if (CurrentUser == null)
            {
                txtEmailAddress.Text = txtUserName.Text.Trim().ToLower() + Convert.ToString(ConfigurationManager.AppSettings["DomainName"]);
            }
            EnableDisableSaveButton(txtUserName);
        }

        private void txtConfirmPassword_TextChanged(object sender, EventArgs e)
        {
            EnableDisableSaveButton(txtConfirmPassword);
        }

        private void txtEmailAddress_TextChanged(object sender, EventArgs e)
        {
            EnableDisableSaveButton(txtEmailAddress);
        }

        #endregion

        #region ButtonEvents

        
        private void crystalButton2_Click(object sender, EventArgs e)
        {
            try
            {
                SaveUser();
            }
            catch (Exception ex)
            {
                this.LogErrorToDatabase(ex);
            }
        }

        private void btnExit_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        #endregion

        #endregion

        #region Methods

        public void GetUserName()
        {

            if (txtFirstName.Text.Trim().Length < 1)
            {
                txtUserName.Text = txtLastName.Text.Trim().ToLower();
            }
            else
            {
                txtUserName.Text = txtFirstName.Text.Trim().Substring(0, 1).ToString() + txtLastName.Text.Trim();
            }
            txtEmailAddress.Text = GetEmailAddress(txtUserName.Text.Trim()).ToLower();

        }

        public string GetEmailAddress(string userName)
        {
            return userName + Convert.ToString(ConfigurationManager.AppSettings["DomainName"]);
        }

        public void FocusOnEmptyControl()
        {
            if (string.IsNullOrEmpty(txtFirstName.Text.Trim()))
            {
                txtFirstName.Focus();
            }
            else if (string.IsNullOrEmpty(txtLastName.Text.Trim()))
            {
                txtLastName.Focus();
            }
            else if (string.IsNullOrEmpty(txtPassword.Text.Trim()))
            {
                txtPassword.Focus();
            }
            else if (string.IsNullOrEmpty(txtConfirmPassword.Text.Trim()))
            {
                txtConfirmPassword.Focus();
            }
            else if (string.IsNullOrEmpty(txtUserName.Text.Trim()))
            {
                txtUserName.Focus();
            }
            else if (string.IsNullOrEmpty(txtEmailAddress.Text.Trim()))
            {
                txtEmailAddress.Focus();
            }
        }

        private bool IsValid()
        {
            if (!this.ValidateChildren())
            {
                FocusOnEmptyControl();
                return true;
            }

            return false;
        }

        private void SaveUser()
        {

            if (IsValid())
            {
                return;
            }
            if (Validation())
            { return; }

            if (CurrentUser == null) { CurrentUser = new USR_Users(); }
            else { UserId = CurrentUser.UserID; }
            CurrentUser.FirstName = txtFirstName.Text.Trim();
            CurrentUser.LastName = txtLastName.Text.Trim();
            CurrentUser.UserName = txtUserName.Text.Trim();
            CurrentUser.Password = txtPassword.Text.Trim();

            CurrentUser.EMailAddress = txtEmailAddress.Text.Trim();
            if (chk.Checked)
            {
                CurrentUser.UserStatus = UserStatus.EXEMP.ToString();
            }
            else
            {
                CurrentUser.UserStatus = UserStatus.ACTVE.ToString();
            }
            if (EveSaveUser != null)
            {
                EveSaveUser();
            }
            if (UserId < 1)
            {
                this.ShowMessageBox(DBResult.INSERTED, BaseClass.Capitalize("user"), DBResult.SUCCESS);
                isNewUser = true;
            }
            else
            {
                this.ShowMessageBox(DBResult.UPDATED, BaseClass.Capitalize("user"), DBResult.SUCCESS);
            }
            isSaved = true;
            this.Close();
        }

        public bool IsEmptyUserDetail()
        {
            if (string.IsNullOrEmpty(txtFirstName.Text.Trim()) && string.IsNullOrEmpty(txtLastName.Text.Trim()) && string.IsNullOrEmpty(txtUserName.Text.Trim()) && string.IsNullOrEmpty(txtPassword.Text.Trim()) && string.IsNullOrEmpty(txtConfirmPassword.Text.Trim()) && !chk.Checked)
            {
                return true;
            }
            return false;
        }

        public void EnableDisableSaveButton(TextBox control)
        {

            if (control.Text.Length <= 0)
            {
                btnSave.Enabled = false;
            }
            else
            {
                btnSave.Enabled = true;
            }
            CheckEmptyTexBox();
        }

        public void CheckEmptyTexBox()
        {
            if (string.IsNullOrEmpty(txtFirstName.Text.Trim()) || string.IsNullOrEmpty(txtLastName.Text.Trim()) || string.IsNullOrEmpty(txtUserName.Text.Trim()) || string.IsNullOrEmpty(txtPassword.Text.Trim()) || string.IsNullOrEmpty(txtConfirmPassword.Text.Trim()) || string.IsNullOrEmpty(txtEmailAddress.Text.Trim()))
            {
                btnSave.Enabled = false;
                
            }
        }
        private bool CompareWithCurrentUser()
        {
            if ((CurrentUser.UserStatus == UserStatus.EXEMP.ToString() && chk.Checked) || (CurrentUser.UserStatus != UserStatus.EXEMP.ToString() && !chk.Checked))
            {
                if (CurrentUser.FirstName == txtFirstName.Text.Trim() && CurrentUser.LastName == txtLastName.Text.Trim() && CurrentUser.UserName == txtUserName.Text.Trim() && CurrentUser.EMailAddress == txtEmailAddress.Text.Trim() && CurrentUser.Password == txtPassword.Text.Trim())
                { return false; }
            }
            return true;
        }

        private void CloseAddEditUserForm(FormClosingEventArgs e)
        {
            DialogResult result;
            if (this.viewMode == ViewMode.AddMode)
            {
                if (IsEmptyUserDetail())
                {
                    return;
                }
                result = CYMessageBox.Show(MessageManager.GetMessage("FILLFORM"), "Exit", CYMessageBox.CustomButtons.OKExit, CYMessageBox.CYIcon.Question);
                if (result == DialogResult.OK)
                {
                    if (IsValid() || Validation())
                    {
                        e.Cancel = true;
                    }
                    else
                    {
                        SaveUser();
                    }
                }
            }
            else
            {
                if (CurrentUser != null)
                {

                    if (CompareWithCurrentUser())
                    {
                        result = CYMessageBox.Show(MessageManager.GetMessage("FILLFORM"), "Exit", CYMessageBox.CustomButtons.OKExit, CYMessageBox.CYIcon.Question);
                        if (result == DialogResult.OK)
                        {
                            if (IsValid())
                            {
                                e.Cancel = true;
                            }
                            else
                            {
                                SaveUser();
                            }
                        }
                    }
                }
            }
        }

        #endregion

        #region Validation

        private void GetValidatedControls()
        {
            ValidateControls(this.Controls,false );

            ////Compare Validation
            this.cmpPassword = new ValidationManager.CompareValidator();
            this.cmpPassword.ControlToValidate = this.txtConfirmPassword;
            this.cmpPassword.ControlToCompare = this.txtPassword;
            this.cmpPassword.ErrorMessage = ShowErrorMessage(DBResult.CONFIRM_PASSWORD, BaseClass.Capitalize("Confirm Password"), BaseClass.Capitalize("Password"));

            //Regular Expression Validation
            this.regEmail = new ValidationManager.RegularExpressionValidator();
            this.regEmail.ControlToValidate = this.txtEmailAddress;
            this.regEmail.ValidationExpression = ValidationManager.regexString(ValidationManager.RegexType.Email);
            this.regEmail.ErrorMessage = ShowErrorMessage(DBResult.INVALID, BaseClass.Capitalize("Email"));

            this.regPassword = new ValidationManager.RegularExpressionValidator();
            this.regPassword.ControlToValidate = this.txtPassword;
            this.regPassword.ValidationExpression = ValidationManager.regexString(ValidationManager.RegexType.AlphaNumeric);
            this.regPassword.ErrorMessage = ShowErrorMessage(DBResult.ALPHANUMERIC_PASSWORD, BaseClass.Capitalize("Password"));
        }

        private bool Validation()
        {
            bool IsUserExist = false;
            int emailCount = 0;

            //Is User Already Exist
            if (CurrentUser != null)
            {
                if (CurrentUser.UserName.ToLower() != txtUserName.Text.Trim().ToLower())
                {
                    IsUserExist = CheckUserName(txtUserName.Text.Trim());
                }
            }
            else
            {
                IsUserExist = CheckUserName(txtUserName.Text.Trim());
            }
            if (IsUserExist)
            {
                txtUserName.Focus();
                ShowMessageBox(DBResult.EXIST, BaseClass.Capitalize("UserName"));
                return true;
            }

            ////Is Email Already Exist
            if (CurrentUser != null)
            {
                if (CurrentUser.EMailAddress != txtEmailAddress.Text.Trim())
                {
                    emailCount = CheckEmailAddress(txtEmailAddress.Text.Trim());
                }
            }
            else
            {
                emailCount = CheckEmailAddress(txtEmailAddress.Text.Trim());
            }

            if (emailCount > 0)
            {
                txtEmailAddress.Focus();
                ShowMessageBox(DBResult.EXIST, BaseClass.Capitalize("Email"));
                return true;
            }
            return false;
        }

        private void UnloadEvents()
        {
            this.CheckEmailAddress -= this.AddUpdatePresenter.view_CheckUserEmail;
            this.CheckUserName -= this.AddUpdatePresenter.view_CheckUserName;
            this.EveSaveUser -= this.AddUpdatePresenter.view_AddEditUser;
        }

        #endregion

        private void crystalButton1_Click(object sender, EventArgs e)
        {
            this.Close();
        }

      
    }
}
